﻿// BaiduOCRService.cs
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace FullApp1.Modules.ModuleName.Models { 
public static class BaiduOCRService
{
    // 从百度云控制台获取的凭证（需要用户自行申请）
    private const string API_KEY = "mS6BRpYQGFux6UZFJUCbpiyk";
    private const string SECRET_KEY = "LV1agLBpRLrLlFT6dsfUZwE9i2wcKdOt";

    // 获取访问令牌
    private static async Task<string> GetAccessToken()
    {
        using (var client = new HttpClient())
        {
            var url = $"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={API_KEY}&client_secret={SECRET_KEY}";
            var response = await client.GetAsync(url);
            var result = await response.Content.ReadAsStringAsync();
            dynamic tokenResult = JsonConvert.DeserializeObject(result);
            return tokenResult?.access_token;
        }
    }

    // 身份证识别通用方法
    public static async Task<BaiduOCRResult> RecognizeIDCard(string imagePath, bool isFrontSide)
    {
        try
        {

                var accessToken = await GetAccessToken();
                var url = $"https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token={accessToken}";

                var client = new Baidu.Aip.Ocr.Ocr(API_KEY, SECRET_KEY);
                client.Timeout = 60000; // 设置超时时间为60秒
                var idCardSide = isFrontSide ? "front" : "back";
                var imageBytes = File.ReadAllBytes(imagePath);
                var response = client.Idcard(imageBytes, idCardSide).ToString();
                var result = JsonConvert.DeserializeObject<BaiduOCRResult>(response);

                //    using (var content = new MultipartFormDataContent())
                //{
                //    // 添加图片参数
                //    var imageBytes = File.ReadAllBytes(imagePath);
                //    content.Add(new ByteArrayContent(imageBytes), "image", "idcard.jpg");
                //    content.Add(new StringContent(isFrontSide ? "front" : "back"), "id_card_side");

                //    // 发送请求
                //    var response = await client.PostAsync(url, content);
                //    var resultJson = await response.Content.ReadAsStringAsync();
                //    var result = JsonConvert.DeserializeObject<BaiduOCRResult>(resultJson);

                //    // 错误处理
                //    if (!string.IsNullOrEmpty(result.Error_Code))
                //    {
                //        throw new Exception($"OCR识别失败：{result.Error_Msg} (错误码：{result.Error_Code})");
                //    }

                return result;
            //}
        }
        catch (Exception ex)
        {
            // 记录日志
            Console.WriteLine($"OCR服务异常：{ex.Message}");
            return new BaiduOCRResult { Error_Msg = ex.Message };
        }
    }
}
}